package com.ajz.security.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.ajz.common.exception.BusinessException;
import com.ajz.common.service.impl.BaseServiceImpl;
import com.ajz.security.dao.RoleDao;
import com.ajz.security.dao.UserDao;
import com.ajz.security.entity.Role;
import com.ajz.security.entity.User;
import com.ajz.security.service.IRoleService;
import com.ajz.security.service.IUserService;

@Transactional
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role, String> implements IRoleService {

	@Autowired
	private RoleDao roleDao;
	@Autowired
	private IUserService iUserService;
	@Autowired
	private UserDao userDao;

	@Override
	public Role save(Role entity) {
		if (null == entity.getId()) {
			Role role = this.findByName(entity.getName());
			if (role != null) {
				throw new BusinessException("权限名已存在！");
			}
		}
		super.save(entity);
		User user = iUserService.findByLoginName("admin");
		if (user != null) {
			List<Role> roles = user.getRoles();
			Assert.notNull(roles);
			roles.add(entity);
			user.setRoles(roles);
			userDao.save(user);
		}
		return entity;
	}

	@Override
	public Role findByName(String name) {
		return roleDao.findByName(name);
	}

	@Override
	public List<Role> findByParentIsNull() {
		return roleDao.findByParentIsNull();
	}

}
